<template>
  <!-- 质量报告记录表单弹窗 -->
  <!-- 上一步 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="110"
      >
        <div v-if="nextStep && !props.isReadonly">
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="报告日期"
                prop="reportDate"
                style="width: 100%"
              >
                <el-date-picker
                  v-if="!props.isReadonly"
                  v-model="formData.reportDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="选择报告日期"
                  style="width: 100%"
                />
                <span v-else>{{ formData.reportDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="客户名称"
                prop="customerName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.customerName"
                  placeholder="请输入客户名称"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.customerName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工厂" prop="plantCode" style="width: 100%">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.plantCode"
                  placeholder="请选择所在工厂"
                  clearable
                  style="width: 100%"
                  @change="plantChange(formData.plantCode)"
                  filterable
                >
                  <el-option
                    v-for="item in plantList"
                    :key="item.id"
                    :label="item.organizationCode"
                    :value="item.organizationCode"
                  />
                </el-select>

                <span v-else>{{ formData.plantCode }}</span>
              </el-form-item></el-col
            >
            <el-col :span="12">
              <el-form-item label="产品" prop="materialId" style="width: 100%">
                <select-content-input
                  v-if="!props.isReadonly"
                  :width="280"
                  :isMultiple="false"
                  :showSelectDevice="materialList"
                  :plantId="formData.plantId"
                  :placeholder="'请选择产品'"
                  :materialType="'3'"
                  :disabled="formData.plantId == ''"
                  @get-device="(id:string[], object:Object) => getDevice(id, object, )"
                />
                <span v-else>{{
                  formData.materialCode + "-" + formData.materialName
                }}</span>
              </el-form-item></el-col
            >

            <el-col :span="12">
              <el-form-item
                label="产品名称"
                prop="materialName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialName"
                  placeholder="请输入产品名称"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.materialName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="图号"
                prop="materialDrawingNo"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialDrawingNo"
                  placeholder="请输入图号"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.materialDrawingNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="批次号"
                prop="materialBatch"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialBatch"
                  placeholder="请输入批次号"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.materialBatch }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="报告类型"
                prop="reportCategory"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.reportCategory"
                  placeholder="请选择报告类型"
                  clearable
                  v-if="!props.isReadonly"
                  filterable
                  style="width: 100%"
                  @change="reportCategoryChange"
                  @click="reportCategoryClick"
                >
                  <el-option
                    v-for="item in useDictionary('QmsReportType')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ formData.reportCategory }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="mb-[20px] mt-[0px]">扩展信息</h4>
          <el-row v-if="formData.reportCategory == '2'">
            <el-col :span="12">
              <el-form-item
                label="检验标准"
                prop="checkLevel"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.checkLevel"
                  placeholder="请输入检验标准"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.checkLevel }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="设备型号"
                prop="deviceType"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.deviceType"
                  placeholder="请输入设备型号"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.deviceType }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="管电压" prop="voltage" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.voltage"
                  placeholder="请输入管电压"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.voltage }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="管电流" prop="electric" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.electric"
                  placeholder="请输入管电流"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.electric }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="分辨率"
                prop="resolution"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.resolution"
                  placeholder="请输入分辨率"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.resolution }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="像素计型号"
                prop="imageQualityMeter"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.imageQualityMeter"
                  placeholder="请输入像素计型号"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.imageQualityMeter }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="像素计灵敏度"
                prop="imageQualitySensi"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.imageQualitySensi"
                  placeholder="请输入像素计灵敏度"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.imageQualitySensi }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 下一步 -->
        <div v-if="!nextStep && !props.isReadonly">
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="报告日期"
                prop="reportDate"
                style="width: 100%"
              >
                <el-date-picker
                  v-if="!props.isReadonly"
                  v-model="formData.reportDate"
                  type="date"
                  placeholder="选择报告日期"
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.reportDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="客户名称"
                prop="customerName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.customerName"
                  placeholder="请输入客户名称"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.customerName }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="产品名称"
                prop="materialName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialName"
                  placeholder="请输入产品名称"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.materialName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="图号"
                prop="materialDrawingNo"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialDrawingNo"
                  placeholder="请输入图号"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.materialDrawingNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="批次号"
                prop="materialBatch"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialBatch"
                  placeholder="请输入批次号"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
                <span v-else>{{ formData.materialBatch }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
            v-if="!props.isReadonly"
          >
            <el-button
              type="success"
              plain
              @click="handleAdd"
              v-if="!props.isReadonly"
            >
              <i-ep-plus />
              新增
            </el-button>
            <div class="mb-[10px] mt-[20px]" style="display: flex">
              <div style="width: 200px; margin-right: 10px">
                <el-form-item label="" prop="plantCode">
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="formData.reportTemplateId"
                    placeholder="请选择模板"
                    clearable
                    style="width: 200px"
                    filterable
                    @change="changeReportTemplate"
                  >
                    <el-option
                      v-for="item in reportTemplateList"
                      :key="item.id"
                      :label="item.reportName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </div>
              <el-button @click="lookReportTemplate"> 查看模板 </el-button>
            </div>
          </div>

          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                label="顺序"
                props=""
                min-width="50"
                type="index"
                align="center"
              >
              </el-table-column>
              <el-table-column
                label="检验项名称"
                props="checkItemName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  {{ row.checkItemName }}
                </template>
              </el-table-column>
              <el-table-column
                label="检验单号"
                props="orderCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.orderCode'"
                    :rules="rules.sonorderCode"
                    label-width="0"
                    @click="openDialogdetail($index, row)"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.orderCode"
                      placeholder="请输入检验单号"
                      clearable
                    >
                      <template #append>搜索</template></el-input
                    >
                    <span v-else>{{ row.orderCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="200"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    v-if="scope.$index != 0"
                    @click.stop="moveUp(scope.$index)"
                    link
                    type="primary"
                  >
                    上移
                  </el-button>
                  <el-button
                    :disabled="formData.details.length < 2"
                    v-if="scope.$index == 0"
                    @click.stop="moveDown(scope.$index)"
                    link
                    type="primary"
                  >
                    下移
                  </el-button>
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 查看明细 -->
        <div v-if="props.isReadonly">
          <el-descriptions
            class="margin-top"
            title=""
            :column="2"
            border
            v-show="props.isReadonly"
          >
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">日期</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.reportDate }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">客户</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.customerName }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">产品名称</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.materialName }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">图号</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.materialDrawingNo }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">批次号</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.materialBatch }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <div></div>
            <div class="mt-[20px]" style="display: flex">
              <el-button @click="previewBtn"> 预览 </el-button>
            </div>
          </div>
          <div class="formTable2" style="margin-top: 10px">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                label="顺序"
                props=""
                min-width="50"
                type="index"
                align="center"
              >
              </el-table-column>
              <el-table-column
                label="检验项名称"
                props="checkItemName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  {{ row.checkItemName }}
                </template>
              </el-table-column>
              <el-table-column
                label="检验单号"
                props="orderCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.orderCode }}</span>
                </template>
              </el-table-column>

              <!-- <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="200"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    v-if="scope.$index != 0"
                    @click.stop="moveUp(scope.$index)"
                    link
                    type="primary"
                  >
                    上移
                  </el-button>
                  <el-button
                    :disabled="formData.details.length < 2"
                    v-if="scope.$index == 0"
                    @click.stop="moveDown(scope.$index)"
                    link
                    type="primary"
                  >
                    下移
                  </el-button>
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="nextStep && !props.isReadonly"
            type="primary"
            :loading="loading"
            @click="nextStepDownBtn"
            >下一步</el-button
          >
          <el-button
            v-if="!nextStep && !props.isReadonly"
            type="primary"
            :loading="loading"
            @click="nextStepUpBtn"
            >上一步</el-button
          >
          <el-button
            v-if="!nextStep && !props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >提交</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 搜索弹窗 -->
    <qualityReportRecordSearch
      :visible="selectLocationDialog.visible"
      :reportList="reportList"
      @change-visible="changeLocationVisible"
    />
    <!-- 模板弹窗 -->
    <qmsTemplateDialog
      :visible="TemplateDialog.visible"
      :data="TemplateDialog.data"
      @change-visible="TemplateDialogVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useTable, useDictionary } from "@/utils/useTable";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { placeholderSign } from "element-plus/es/components/table-v2/src/private";
const dictionaryStore = useDictStoreHook();
import { useRouter, useRoute } from "vue-router";
import { log } from "console";

const router = useRouter();
const route = useRoute();

defineOptions({
  name: "QMSQMSREPORTRECORDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  reportCode: "",
  customerId: "",
  customerName: "",
  materialBatch: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  materialDrawingNo: "",
  materialQuality: "",
  processId: "",
  processName: "",
  processCode: "",
  projectId: "",
  projectName: "",
  projectCode: "",
  reportCategory: "",
  reportDate: "",
  deviceType: "",
  checkLevel: "",
  voltage: "",
  electric: "",
  resolution: "",
  imageQualityMeter: "",
  imageQualitySensi: "",
  approveStatus: "",
  approveUserId: "",
  approveUserName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  // ====后加的工厂
  plantId: "",
  plantName: "",
  plantCode: "",
  reportTemplateId: "",
  details: [
    {
      id: "",
      reportRecordId: "",
      reportTemplateId: "",
      checkItemId: "",
      checkItemName: "",
      orderCode: "",
      orderId: "",
      checkType: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
  materialList: [
    {
      id: "",
      materialName: "",
      materialCode: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  version: [],
  reportCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  customerId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  customerName: [
    {
      required: true,
      message: "请输入客户名称",
      trigger: "blur",
    },
  ],
  plantCode: [
    {
      required: true,
      message: "请选择工厂",
      trigger: "change",
    },
  ],
  materialBatch: [
    {
      required: true,
      message: "请输入批次号",
      trigger: "blur",
    },
  ],
  materialId: [
    {
      required: true,
      message: "请选择产品",
      trigger: "change",
    },
  ],

  reportCategory: [
    {
      required: true,
      message: "请选择报告类型",
      trigger: "change",
    },
  ],
  reportDate: [
    {
      required: true,
      message: "请选择日期",
      trigger: "change",
    },
  ],
  deviceType: [
    // {
    //   required: true,
    //   message: "请输入设备型号",
    //   trigger: "blur",
    // },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  checkLevel: [
    // {
    //   required: true,
    //   message: "请输入检测标准",
    //   trigger: "blur",
    // },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  voltage: [
    // {
    //   required: true,
    //   message: "请输入管电压",
    //   trigger: "blur",
    // },
    {
      trigger: "blur",
      validator: validator,
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  electric: [
    // {
    //   required: true,
    //   message: "请输入管电流",
    //   trigger: "blur",
    // },
    {
      trigger: "blur",
      validator: validator,
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  resolution: [
    // {
    //   required: true,
    //   message: "请输入分辨率",
    //   trigger: "blur",
    // },
    {
      trigger: "blur",
      validator: validator,
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  imageQualityMeter: [
    // {
    //   required: true,
    //   message: "请输入像质计型号",
    //   trigger: "blur",
    // },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  imageQualitySensi: [
    // {
    //   required: true,
    //   message: "请输入像质计灵敏度",
    //   trigger: "blur",
    // },
    {
      trigger: "blur",
      validator: validator,
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonorderCode: [
    {
      required: true,
      message: "请输入检验单号",
      trigger: "change",
    },
  ],
});

function validator(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过
    return true;
  } else {
    if (/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入最多2位小数及正数"));
    }
  }
}

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  reportRecordId: "",
  reportTemplateId: "",
  checkItemId: "",
  checkItemName: "",
  orderCode: "",
  orderId: "",
  checkType: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  if (formData.reportTemplateId) {
    let sondata = JSON.parse(JSON.stringify(details));
    formData.details.push(sondata);
  } else {
    ElMessage({
      message: "请先选择模板",
      type: "warning",
    });
  }
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        materialList.value[0] = {
          id: formData.id,
          materialCode: formData.materialCode,
          materialName: formData.materialName,
        };
        getReportTemplateList();
      }
    }
  }
);

// 获取选中的数据进行回显并赋值
const materialList: any = ref([
  {
    id: "",
    materialCode: "",
    materialName: "",
  },
]);
function getDevice(Ids: string[], Objects: any) {
  console.log(Objects[0]);
  formData.materialId = Objects[0].id;
  formData.materialCode = Objects[0].materialCode;
  formData.materialName = Objects[0].materialName;
  formData.materialQuality = Objects[0].materialQuality;
  formData.materialDrawingNo = Objects[0].figureNumber;
  // formData.materialList.id = Objects[0].materialId;
  // formData.materialList.materialCode = Objects[0].materialCode;
  // formData.materialList.materialName = Objects[0].materialName;
  materialList.value[0] = {
    id: Objects[0].id,
    materialCode: Objects[0].materialCode,
    materialName: Objects[0].materialName,
  };
  console.log(formData.materialList);
}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.reportCode = "";
  formData.customerId = "";
  formData.customerName = "";
  formData.materialBatch = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.materialDrawingNo = "";
  formData.materialQuality = "";
  formData.processId = "";
  formData.processName = "";
  formData.processCode = "";
  formData.projectId = "";
  formData.projectName = "";
  formData.projectCode = "";
  formData.reportCategory = "";
  formData.reportDate = "";
  formData.deviceType = "";
  formData.checkLevel = "";
  formData.voltage = "";
  formData.electric = "";
  formData.resolution = "";
  formData.imageQualityMeter = "";
  formData.imageQualitySensi = "";
  formData.approveStatus = "";
  formData.approveUserId = "";
  formData.approveUserName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  //
  formData.plantId = "";
  formData.plantName = "";
  formData.plantCode = "";
  formData.reportTemplateId = "";

  materialList.value[0].id = "";
  materialList.value[0].materialName = "";
  materialList.value[0].materialCode = "";
  nextStep.value = true;
}

const loading = ref(false);

/** 质量报告记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      console.log("formData", toRaw(formData));

      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/qmsreportrecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/qms/qmsreportrecord/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};

// 当选择工厂时
const plantChange = (plantCode: string) => {
  for (let i = 0; i < plantList.value.length; i++) {
    if (plantList.value[i].organizationCode == plantCode) {
      formData.plantId = plantList.value[i].id;
      formData.plantName = plantList.value[i].organizationName;
    }
  }
  formData.materialList = [
    {
      id: "",
      materialName: "",
      materialCode: "",
    },
  ];
};
// 选择报告类型
const reportCategoryChange = (e) => {
  formData.checkLevel = "";
  formData.deviceType = "";

  formData.voltage = "";
  formData.electric = "";
  formData.resolution = "";
  formData.imageQualityMeter = "";
  formData.imageQualitySensi = "";

  //

  formData.reportTemplateId = "";
  formData.details = [];

  // if (e) {
  //   if (formData.details.length > 0) {
  //     ElMessageBox.confirm("切换后会重置检验单,是否切换?", "警告", {
  //       confirmButtonText: "确定",
  //       cancelButtonText: "取消",
  //       type: "warning",
  //     })
  //       .then(async () => {
  //         formData.reportTemplateId = "";
  //         formData.details = [];
  //       })
  //       .catch(() => {
  //         formData.reportCategory = formData.reportCategory;
  //       });
  //   }
  // }
};

const reportCategoryClick = (e) => {
  console.log("eClick", e);
};
// 定义上一步 下一步

const nextStep = ref(true);
// 下一步
const nextStepDownBtn = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      await getReportTemplateList();
      nextStep.value = false;
    }
  });
};
// 上一步
const nextStepUpBtn = () => {
  nextStep.value = true;
};

// 切换模板
const changeReportTemplate = () => {
  formData.details = [];
};

// 查看模板
const lookReportTemplate = () => {
  if (formData.reportTemplateId) {
    // TemplateDialog.data = {};
    // TemplateDialog.visible = true;

    reportTemplateList.value.forEach((item) => {
      if (item.id == formData.reportTemplateId) {
        router.push({ path: item.templateRoute });
      }
    });
  } else {
    ElMessage({
      message: "请先选择模板",
      type: "warning",
    });
  }
};

// 获取模板
const reportTemplateList: any = ref([]);
const getReportTemplateList = async () => {
  const res1 = await request({
    url: "qms/qmsreporttemplate/getList",
    method: "post",
    data: { reportCategory: formData.reportCategory },
  });
  reportTemplateList.value = res1.data;
  console.log("reportTemplateList", reportTemplateList.value);
};

// 打开搜索弹窗
const selectLocationDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开质量报告记录表单弹窗 详情 */
const rowIndex = ref();
function openDialogdetail(index, roleObj?: any) {
  selectLocationDialog.title = "搜索检验项";
  selectLocationDialog.visible = true;
  rowIndex.value = index;
}

// function changeVisible(value: boolean) {
//   selectLocationDialog.visible = value;
//   if (!value) {
//     addDialog.data = {};
//   }
// }
const changeLocationVisible = (val: boolean, data: any) => {
  if (data) {
    console.log("返回的数据", data);
    // formData.details = [];
    // data.forEach((item, index) => {
    //   formData.details.push({
    //     locationId: item.id,
    //     locationCode: item.locationCode,
    //     locationName: item.locationName,
    //     sort: index + 1,
    //   });
    // });

    formData.details[rowIndex.value].orderId = data.id;
    // formData.details[rowIndex.value].reportTemplateId =
    //   formData.reportTemplateId;
    formData.details[rowIndex.value].checkItemId = data.checkItemId;
    formData.details[rowIndex.value].checkItemName = data.checkItemName;
    formData.details[rowIndex.value].orderCode = data.orderNo;
    console.log(formData.details);

    // formData.details[rowIndex.value].orderId = data.id;
    // formData.details[rowIndex.value].checkType = data.id;
  }
  selectLocationDialog.visible = val;
};

const reportList = ref([]);

// 上移
const moveUp = (index) => {
  if (index > 0) {
    let item1 = formData.details[index];
    let item2 = formData.details[index - 1];
    formData.details.splice(index - 1, 1, item1);
    formData.details.splice(index, 1, item2);
  }
};
// 下移
const moveDown = (index) => {
  if (index < formData.details.length - 1) {
    let item1 = formData.details[index];
    let item2 = formData.details[index + 1];
    formData.details.splice(index + 1, 1, item1);
    formData.details.splice(index, 1, item2);
  }
};

// 预览弹窗

const TemplateDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const TemplateDialogVisible = (val: boolean) => {
  TemplateDialog.visible = val;
  TemplateDialog.data = {};
};

const previewBtn = () => {
  // TemplateDialog.data = row;
  // TemplateDialog.visible = true;

  // TemplateDialog.data = {};
  // TemplateDialog.visible = true;

  reportTemplateList.value.forEach((item) => {
    if (formData.reportTemplateId == item.id) {
      router.push({ path: item.templateRoute, query: { id: formData.id } });
    }
  });
};

onMounted(() => {
  getPlantList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
  :deep(.el-scrollbar__wrap) {
    max-height: 290px;
    overflow-y: auto;
  }
}

.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
